#!/usr/bin/env Rscript
################################
## Generalization Error
## estimation for fraud paper
## Block bootstrap, forensic 
## features 
################################




# Flag to send job to cluster or 
# run in a regular computer (still in parallel,
# using MPI backend)
PegasusRun  <- commandArgs()

if(PegasusRun){
  system("bsub < GenErrorBootFull.job")
}else{
  #!/usr/bin/env Rscript
  
  ## Load libraries on all cores
  library(plyr)
  library(foreach)
  library(doMPI)
  
  ## Seed RNG
  set.seed(831213)
  
  ## Start cluster & worker loop
  cl  <- startMPIcluster()
  registerDoMPI(cl)
  
  ## Load libraries on master
  library(BayesTree)
  library(glmnet)
  
  
  ## Load auxiliary functions
  source("./GenErrorAuxFunc.R")
  
  ## Get processed data
  load("./FullData.RData")
  
  
  ## Estimate bootstrap generalization errors
  ## Set nr. of bootstrap samples
  n.boot.samp <- 150
  
  ## Get best parameters from parameter sweep
  bestParams <- read.csv("./BSParamSweep.csv"
                         ,nrows=1
  )[,1:6]
  bartParams  <- expand.grid(k=bestParams$k
                             ,pow=bestParams$pow
                             ,base=bestParams$base
                             ,sigdf=bestParams$sigdf
                             ,sigquant=bestParams$sigquant
                             ,ntree=bestParams$ntree
                             ,sampind=1:n.boot.samp
                             ,burnin=50e3
                             ,niter=5e3
                             ,keepevery=10)
  bartParams  <- as.matrix(bartParams)
  
  ## Estimate generalization errors
  ## For full model
  ## using 150 bootstrap block samples
  full.errors.boot <- err.generator(n.boot.samp
                                    ,bartParams
                                    ,all.data$fData
                                    ,all.data$countries.full
                                    ,parallel=TRUE)
  
  ## Save results
  save(full.errors.boot
       ,file="./GenErrorsBootFull.RData")
  
  closeCluster(cl)
  mpi.finalize()
}


